<template>
    <div id="app">
        <Header notab=""/>
        <div class="contentWeb">
            <div style="background: #fff; padding: 40px; margin-top: 30px;">
                <h2 style="margin-bottom: 45px;">个人用户注册</h2>
                <el-form ref="form" :model="form" :rules="rules" label-width="180px" style="margin-top: 20px;">
                    <el-form-item label="用户名" prop="account">
                        <el-input placeholder="请输入" autocomplete="off" v-model="form.account" style="width: 600px"/>
                        <span class="tishiy">6-16位英文或数字</span>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" placeholder="请输入" autocomplete="off" v-model="form.password"
                                  style="width: 600px"/>
                        <span class="tishiy">6-16位字母与数字的组合</span>
                    </el-form-item>
                    <el-form-item label="重复密码" required>
                        <el-input type="password" placeholder="请输入" autocomplete="off" v-model="password2"
                                  style="width: 600px"/>
                        <span class="tishiy" style="color: red">{{passtext}}</span>
                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realName">
                        <el-input placeholder="请输入" v-model="form.realName" style="width: 600px"/>
                        <span class="tishiy">请确保填写信息真实有效</span>
                    </el-form-item>
                    <el-form-item label="身份证号" prop="identifyCode">
                        <el-input placeholder="请输入" v-model="form.identifyCode" style="width: 600px"/>
                        <span class="tishiy">请确保填写信息真实有效</span>
                    </el-form-item>
                    <el-form-item label="身份证" prop="idCard">
                        <div class="uploadimg" >
                            <el-upload
                              v-loading="frontLoading"
                                name="enterprise_licence"
                                class="avatar-uploader"
                                :action="uploadLicence"
                                :show-file-list="false"
                                :on-success="frontSuccess"
                                accept=".jpg,.png"
                                :before-upload="beforeFrontUpload">
                                <img v-if="form.sfzZm" :src="form.sfzZm" class="avatar"
                                     :style="uplaodstyle">
                                <i v-else class="el-icon-plus avatar-uploader-icon" :style="uplaodstyle"></i>
                                <div slot="tip" class="el-upload__tip">支持格式：jpg、png
                                  <span class="mark">正面</span>
                                </div>
                            </el-upload>
                        </div>
                        <div class="uploadimg" >
                            <el-upload
                              v-loading="backLoading"
                                name="enterprise_licence"
                                class="avatar-uploader"
                                :action="uploadLicence"
                                :show-file-list="false"
                                :on-success="backSuccess"
                                accept=".jpg,.png"
                                :before-upload="beforeBackUpload">
                                <img v-if="form.sfzFm" :src="form.sfzFm" class="avatar"
                                     :style="uplaodstyle">
                                <i v-else class="el-icon-plus avatar-uploader-icon" :style="uplaodstyle"></i>
                                <div slot="tip" class="el-upload__tip">
                                  <span class="mark" style="bottom:-14px;">反面</span>
                                </div>
                            </el-upload>
                        </div>
                        <span class="tishiy">个人和东港人社网后台系统可见</span>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobileNum">
                        <el-input placeholder="请输入" v-model="form.mobileNum" style="width: 600px"/>
                        <span class="tishiy">请确保填写信息真实有效</span>
                    </el-form-item>
                    <el-form-item label="短信验证码" prop="smsCode">
                        <el-input placeholder="请输入" v-model="form.smsCode" style="width: 370px"/>
                        <el-button :disabled="sendCode > 0 ?true: false" @click="sendSms"
                                   style="background: #20a2b2; width: 200px; border: 0; margin-left: 30px;"
                                   type="primary">{{sendCode ? sendCode+'秒后可再次获取' : '点击获取验证码'}}
                        </el-button>
                    </el-form-item>
                    <el-form-item style="margin-top: 60px">
                        <el-button style="background: #20a2b2; width: 300px; border: 0; margin-left: 150px;"
                                   type="primary"
                                   @click="onSubmit('form')">保存
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <Footer/>
    </div>
</template>
<script type="text/babel">
// @ is an alias to /src
import util from '../../assets/js/util'
import Header from '../../components/header'
import Footer from '../../components/footer'
import { useregister, CompanyRegisterDelete, sendMessage, uploadLicence, GetUrlParam } from '../../assets/js/domains'

export default {
  name: 'Company',
  components: {
    Header,
    Footer
  },
  directives: {},
  data: function () {
    return {
      uploadLicence,
      uplaodstyle: {
        width: '160px',
        height: '160px'
      },
      rules: {
        smsCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { validator: this.checkname, trigger: 'blur' },
          { validator: this.validSensWords, trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { validator: this.validSensWords, trigger: 'blur' }
        ],
        identifyCode: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: this.checkcard, trigger: 'blur' }
        ],
        mobileNum: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: this.phonechange, trigger: 'blur' }
        ],
        idCard: [
          { required: true, validator: this.checkIdCard, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: this.validatePass, trigger: 'blur' }
        ]
      },
      password2: '',
      frontLoading: false,
      backLoading: false,
      form: {
        account: '',
        password: '',
        email: '',
        addressDetail: '',
        realName: '',
        identifyCode: '',
        sfzZm: '',
        sfzFm: '',
        mobileNum: '',
        smsCode: ''
      },
      passtext: '',
      smsCode: '',
      sendCode: 0,
      uid: ''
    }
  },
  created: function () {
    document.title = '注册'
  },
  computed: {},
  mounted: function () {
    this.uid = GetUrlParam('uid')
    if (this.uid) {
      const curUserInfo = JSON.parse(localStorage.getItem('md_userInfo'))
      Object.keys(this.form).forEach(key => {
        this.form[key] = curUserInfo[key]
      })
      this.form.password = ''
    }
  },
  methods: {
    checkname: function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        var myreg = '^[0-9a-zA-Z]{6,12}$'
        var re = new RegExp(myreg)
        if (!re.test(value)) {
          callback(new Error('请输入6-16位英文或数字'))
        } else {
          callback()
        }
      }
    },
    checkIdCard: function (rule, value, callback) {
      if (!this.form.sfzZm) {
        return callback(new Error('请上传身份证正面照'))
      }
      if (!this.form.sfzFm) {
        return callback(new Error('请上传身份证反面照'))
      }
      callback()
    },
    checkcard: function (rule, value, callback) {
      if (!util.isIdCode(value)) {
        return callback(new Error('请输入正确的身份证号'))
      }
      callback()
    },
    phonechange: function (rule, value, callback) {
      if (!util.isMobile(value)) {
        return callback(new Error('请输入正确的手机号'))
      }
      callback()
    },
    validatePass: function (rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/
        var re = new RegExp(reg)
        if (re.test(value)) {
          callback()
        } else {
          callback(new Error('密码格式不正确,请输入6-16位字母与数字的组合'))
        }
      }
    },
    frontSuccess: function (e) {
      const _this = this
      this.frontLoading = false
      if (e.code === 200) {
        _this.form.sfzZm = e.data
        _this.form = Object.assign({}, _this.form)
      }
    },
    backSuccess: function (e) {
      const _this = this
      this.backLoading = false
      if (e.code === 200) {
        _this.form.sfzFm = e.data
        _this.form = Object.assign({}, _this.form)
      }
    },
    beforeFrontUpload: function (file) {
      this.frontLoading = true
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 jpg或png 格式!')
        this.frontLoading = false
      }
    },
    beforeBackUpload: function (file) {
      this.backLoading = true
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 jpg或png 格式!')
        this.backLoading = false
      }
    },
    delRegInfo () {
      const userInfo = JSON.parse(localStorage.getItem('md_userInfo'))
      if (!userInfo) {
        return false
      }
    },
    onSubmit (form) {
      const _this = this
      this.$refs[form].validate(valid => {
        if (!valid) {
          return false
        }
        if (_this.form.password !== _this.password2) {
          _this.passtext = '密码不一致，请重新输入'
          _this.$message({
            type: 'error',
            message: '密码不一致，请重新输入'
          })
          return false
        }
        // todo
        if (_this.smsCode !== _this.form.smsCode) {
          _this.$message.error('短信验证码不正确！')
          return false
        }
        const form = Object.assign({}, _this.form)
        form.password = util.strEncode(form.password)
        delete form.password2
        if (!this.uid) {
          this.userReg(form)
          return
        }
        this.updateRegInfo(form)
      })
    },
    userReg (form) {
      useregister(form).then(res => {
        if (res.code !== 200) {
          this.$alert(res.msg, '提示')
          return
        }
        this.$alert('注册成功', '提示', {
          confirmButtonText: '确定',
          callback: function () {
            localStorage.setItem('showlogin', 1)
            window.location.href = 'index.html'
          }
        })
      })
    },
    updateRegInfo (form) {
      CompanyRegisterDelete({ delete_id: this.curUserInfo.id }).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message || '用户信息注销失败！')
          return
        }
        this.userReg(form)
      })
    },
    sendSms: function () {
      var _this = this
      if (!this.form.mobileNum) {
        _this.$message.error('请输入手机号码')
        return
      }
      if (!util.isMobile(this.form.mobileNum)) {
        _this.$message.error('手机号码格式不正确')
        return
      }
      sendMessage({ phoneNumber: this.form.mobileNum }).then(function (res) {
        if (res.code === 200) {
          _this.sendCodeInterval()
          _this.smsCode = res.data
        }
      })
    },
    sendCodeInterval: function () {
      this.sendCode = 60
      var _this = this
      var intervalHanlder = setInterval(function () {
        _this.sendCode -= 1
        if (_this.sendCode <= 0) {
          clearInterval(intervalHanlder)
        }
      }, 1000)
    }
  }
}
</script>
<style lang="less">
.upload{
  background-color: #20A2B2;
  color: white;
  border: 1px solid #20A2B2;
  &:hover{
    background-color: #20A2B2;
  }
}

.uploadimg {
  float: left;
  display: inline-block;
  border-radius: 5px;
  background-color: #FDFDFD;
  margin-right: 10px;
  position: relative;
  .mark{
    position:absolute;
    bottom: 25px;
    left: 75px;
  }
  .avatar-uploader{display: inline-block; }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: inline-block;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}

</style>
